﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections;
using SmartSpace.UI.Silverlight.Dynamic.DynamicRef;
using System.Collections.ObjectModel;
using System.Windows.Browser;
using SmartSpace.UI.Silverlight;

namespace SmartSpace.UI.Silverlight.Dynamic.Controls
{
    /// <summary>
    /// 附件控件
    /// 包含上传和下载功能
    /// </summary>
    public partial class AttachmentControl : PMFDataControl, IAsyncControl
    {
        private string m_filter = "所有文件 | *.*";
        public event Action<bool, FrameworkElement> SaveDataFail;
        private List<Attachment> _selectedAttachments;

        public AttachmentControl()
        {
            InitializeComponent();
        }

        #region Overrides

        public override void UpdateSource()
        {
            //if (m_datePicker.SelectedDate != null)
            //{
            //    DataSource.Value = m_datePicker.SelectedDate.Value.ToString("yyyy-MM-dd");
            //    DataSource.Text = DataSource.Value;
            //}
            this.GetBindingExpression(PMFDataControl.DataSourceProperty).UpdateSource();
        }


        protected override void OnIsReadOnlyChanged(bool isReadOnly)
        {
            if (isReadOnly)
            {
                m_stackBar.Visibility = System.Windows.Visibility.Collapsed;
                m_datagrid.Columns[1].Visibility = System.Windows.Visibility.Collapsed;
                m_datagrid.Columns[2].Visibility = System.Windows.Visibility.Collapsed;

            }
            else
            {
                m_stackBar.Visibility = System.Windows.Visibility.Visible;
                m_datagrid.Columns[1].Visibility = System.Windows.Visibility.Visible;
                m_datagrid.Columns[2].Visibility = System.Windows.Visibility.Visible;
            }
        }

        protected override void OnDataSourceChanged(FieldInstance dataSource)
        {
            if (!string.IsNullOrEmpty(dataSource.Text))
            {
                //m_datePicker.SelectedDate = Convert.ToDateTime(dataSource.Text);
            }
        }

        #endregion

        #region save operate
        public void SaveData()
        {
            //AttachmentControlUtil.SaveData(this);
        }

        public void OnSaveComplete()
        {
            //ObservableCollection<Attachment> attachments = this.ItemsSource as ObservableCollection<Attachment>;
            //List<Attachment> selectedAttachments = new List<Attachment>();
            //foreach (Attachment info in attachments)
            //{
            //    if (info.Id != default(Guid))
            //    {
            //        selectedAttachments.Add(info);
            //    }
            //}
            //SelectedAttachments = selectedAttachments;

            //if (SaveDataComplete != null)
            //{
            //    SaveDataComplete(this);
            //}
        }

        public void OnSaveFail()
        {
            if (SaveDataFail != null)
            {
                SaveDataFail(false, this);
            }
        }

        public event Action<FrameworkElement> SaveDataComplete;

        private void m_buttonBrowse_Click(object sender, RoutedEventArgs e)
        {
            //OpenFileDialog dlg = new OpenFileDialog();
            //dlg.Filter = m_filter;

            //try
            //{
            //    if ((bool)dlg.ShowDialog())
            //    {
            //        this.Focus();

            //        Attachment model = new Attachment();
            //        model.FileName = dlg.File.Name;
            //        //model.IsUploaded = false;
            //        //model.FileInfo = dlg.File;

            //        if (dlg.File.Length == 0)
            //        {
            //            MessageService.ShowMessage(MessageType.Warrning,string.Format("单个文件 '{0}' 为空文件，添加失败。", dlg.File.Name));
            //            OnSaveFail();
            //            return;
            //        }
            //        else if (!CheckFileLength(dlg.File.Length))
            //        {
            //            MessageService.ShowMessage(MessageType.Warrning, string.Format("单个文件 '{0}' 过大，添加失败。", dlg.File.Name));
            //            OnSaveFail();
            //            return;
            //        }

            //        if (!CheckFileIsExist(dlg.File.Name))
            //        {
            //            ObservableCollection<Attachment> attachments = this.ItemsSource as ObservableCollection<Attachment>;
            //            attachments.Add(model);

            //            this.ItemsSource = null;
            //            this.ItemsSource = attachments;
            //        }
            //    }
            //}
            //catch (Exception ex)
            //{
            //    MessageService.ShowMessage(MessageType.Warrning,ex.Message);
            //    OnSaveFail();
            //}
        }

        /// <summary>
        /// 验证文件是否已存在
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        private bool CheckFileIsExist(string fileName)
        {
            //ObservableCollection<Attachment> attachments = this.ItemsSource as ObservableCollection<Attachment>;
            //foreach (Attachment attachmentModel in attachments)
            //{
            //    if (attachmentModel.FileName.Equals(fileName))
            //    {
            //        MessageService.ShowMessage(MessageType.Warrning,string.Format("文件 '{0}' 已经存在，请选择其它文件进行保存。", fileName));
            //        OnSaveFail();
            //        return true;
            //    }
            //}
            return false;
        }

        /// <summary>
        /// 验证文件长度
        /// </summary>
        /// <param name="fileLength"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        private bool CheckFileLength(long fileLength)
        {
            if (fileLength >= 40 * 1024 * 1024)
            {
                return false;
            }
            return true;
        }

        private void m_buttonDelete_Click(object sender, RoutedEventArgs e)
        {
            //ObservableCollection<Attachment> attachments = this.ItemsSource as ObservableCollection<Attachment>;
            //HyperlinkButton button = sender as HyperlinkButton;
            //Attachment info = button.DataContext as Attachment;
            //if (attachments != null)
            //{
            //    if (MessageBox.Show("是否删除附件?", "提示", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            //    {
            //        attachments.Remove(info);
            //    }
            //}
        }

        /// <summary>
        /// 下载附件操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnHyperlinkButtonDownloadClick(object sender, RoutedEventArgs e)
        {
            Attachment model = (sender as HyperlinkButton).DataContext as Attachment;
            if (model != null)
            {
                HtmlPopupWindowOptions options = new HtmlPopupWindowOptions();
                options.Width = 100;
                options.Height = 50;
                string queryString = String.Format("?id={0}", model.Id);
                HtmlPage.PopupWindow(new Uri(DynamicModule.HostUrl + "WebServices/DownloadAttachment.aspx" + queryString, UriKind.RelativeOrAbsolute),
                    "",
                    options);
            }
        }
        #endregion
    }
}
